import { cloneDeep } from "@pureadmin/utils";
import lodash from "lodash";
import { PxMessageBox } from "px-ui";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { onBeforeRouteLeave } from "vue-router";

function isEmpty(value) {
  if (value === undefined || value === null) {
    return true;
  }
  if (Array.isArray(value) && value.length === 0) {
    return true;
  }
  if (typeof value === "object" && Object.keys(value).length === 0) {
    return true;
  }
  if (typeof value === "string" && value.trim() === "") {
    return true;
  }
  return false;
}
function cleanObject(obj) {
  if (Array.isArray(obj)) {
    // 处理数组
    return obj.map(item => cleanObject(item)).filter(item => !isEmpty(item));
  } else if (obj && typeof obj === "object") {
    // 处理对象
    Object.keys(obj).forEach(key => {
      const value = obj[key];
      if (isEmpty(value)) {
        delete obj[key];
      } else {
        cleanObject(value);
      }
    });
    // 如果对象是空的，则返回 undefined 以便在父级中被删除
    return isEmpty(obj) ? undefined : obj;
  }
  // 其他类型（如字符串、数字、布尔值等）直接返回
  return obj;
}
/**
 *
 * @param {object} params
 * @param {object} params.message 弹窗提示信息，如需动态设置，请使用setMessage
 * @param {object} params.title 弹窗提示标题，如需动态设置，请使用setTite
 * @param {object} params.formValue form表单值
 * @returns
 */
export const useBeforeRouteLeave = (params: { message?: string; title?: string; defaultValue?: any } = {}) => {
  const { message = "您有未保存的更改，确定要离开此页面吗？", title = "提示", defaultValue } = params;
  const isFormDirty = ref(false);
  const messageInfo = ref("");
  const titleInfo = ref("");
  const defaultFormValue = ref();
  const customFormValue = ref<any>({});
  const handleBeforeUnload = event => {
    if (isFormDirty.value) {
      // 设置returnValue可以触发浏览器的离开页面警告
      // 但注意，现代浏览器通常不会显示自定义消息
      event.returnValue = messageInfo.value || message;
      // 有些浏览器可能也支持直接返回字符串（但不是所有）
      return event.returnValue;
    }
  };
  const printFormValue = () => {
    console.log(defaultFormValue.value, customFormValue.value, "printFormValue");
  };
  onMounted(() => {
    if (defaultValue) {
      defaultFormValue.value = cloneDeep(defaultValue);
      customFormValue.value = cloneDeep(defaultValue);
    }
    window.addEventListener("beforeunload", handleBeforeUnload);
  });
  watch(
    [defaultFormValue, customFormValue],
    () => {
      if (defaultFormValue.value) {
        const oldValue = cloneDeep(defaultFormValue.value);
        const newValue = cloneDeep(customFormValue.value);
        const isSame = lodash.isEqual(cleanObject(oldValue), cleanObject(newValue));
        isFormDirty.value = !isSame;
      }
    },
    { deep: true }
  );
  onBeforeUnmount(() => {
    isFormDirty.value = false;
    window.removeEventListener("beforeunload", handleBeforeUnload);
  });

  // 组件内守卫：在离开当前路由之前调用
  onBeforeRouteLeave((to, from, next) => {
    if (isFormDirty.value) {
      // 如果有未保存的更改，显示一个确认对话框
      PxMessageBox.confirm(messageInfo.value || message, titleInfo.value || title, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }).then(async () => {
        isFormDirty.value = false;
        next();
        //  handleGoBack();
      });
    } else {
      // 没有未保存的更改，直接允许路由改变
      next();
    }
  });
  return {
    isFormDirty,
    formValue: customFormValue,
    setIsFormDirty: val => {
      isFormDirty.value = val;
    },
    setMessage: val => {
      messageInfo.value = val;
    },
    setTitle: val => {
      titleInfo.value = val;
    },
    setDefaultValue: val => {
      defaultFormValue.value = cloneDeep(val);
      customFormValue.value = cloneDeep(val);
    },
    printFormValue
  };
};
